<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宠物用品代购 - 宠物家政服务</title>
    <link rel="stylesheet" href="styles/main.css">
    <link rel="stylesheet" href="styles/service-page.css">
    <style>
        /* 页面专属样式 */
        .product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 25px;
        }
        .product-card {
            background: #fff;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(255, 215, 0, 0.1);
            transition: all 0.3s ease;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(255, 215, 0, 0.2);
        }
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }
        .product-info {
            padding: 15px;
        }
        .product-info h4 {
            font-size: 16px;
            margin-bottom: 10px;
            height: 48px; /* 限制2行 */
        }
        .product-price {
            font-size: 18px;
            font-weight: bold;
            color: #d4a200;
        }
        .add-to-cart {
            width: 100%;
            margin-top: 15px;
        }
        .loading {
            text-align: center;
            padding: 40px 0;
            color: #666;
        }
        .error {
            text-align: center;
            padding: 40px 0;
            color: #ef4444;
        }
        
        /* 购物车图标样式 */
        .cart-icon {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: #d4a200;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 4px 16px rgba(212, 162, 0, 0.3);
            transition: all 0.3s ease;
            z-index: 1000;
        }
        .cart-icon:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(212, 162, 0, 0.4);
        }
        .cart-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ef4444;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        /* 购物车弹窗样式 */
        .cart-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1001;
        }
        .cart-modal.show {
            display: flex;
        }
        .cart-content {
            background: white;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }
        .cart-header {
            background: #d4a200;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cart-header h3 {
            margin: 0;
            font-size: 18px;
        }
        .close-btn {
            background: none;
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .cart-body {
            padding: 20px;
            max-height: 400px;
            overflow-y: auto;
        }
        .cart-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }
        .cart-item:last-child {
            border-bottom: none;
        }
        .cart-item-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 15px;
        }
        .cart-item-info {
            flex: 1;
        }
        .cart-item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .cart-item-price {
            color: #d4a200;
            font-weight: bold;
        }
        .cart-item-quantity {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 5px;
        }
        .quantity-btn {
            background: #f0f0f0;
            border: none;
            width: 25px;
            height: 25px;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .quantity-btn:hover {
            background: #e0e0e0;
        }
        /* 新增：美化删除按钮 */
        .delete-btn {
            background: #ef4444;
            border: none;
            color: #fff;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 14px;
            cursor: pointer;
            transition: background 0.2s, transform 0.2s;
            font-size: 16px;
        }
        .delete-btn:hover {
            background: #d32f2f;
            transform: scale(1.12);
        }
        .cart-footer {
            padding: 20px;
            border-top: 1px solid #eee;
            background: #f9f9f9;
        }
        .cart-total {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            font-weight: bold;
            font-size: 18px;
        }
        .cart-actions {
            display: flex;
            gap: 10px;
        }
        .cart-actions .btn {
            flex: 1;
        }
        .empty-cart {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }
        /* 返回按钮样式 */
        .back-btn {
            position: fixed;
            top: 24px;
            left: 24px;
            z-index: 1100;
            display: flex;
            align-items: center;
            background: rgba(255,255,255,0.95);
            color: #d4a200;
            font-size: 18px;
            padding: 8px 18px 8px 12px;
            border-radius: 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            text-decoration: none;
            font-weight: bold;
            transition: background 0.2s, color 0.2s;
        }
        .back-btn i {
            margin-right: 8px;
            font-size: 20px;
        }
        .back-btn:hover {
            background: #fffbe6;
            color: #b38a00;
        }
    </style>
</head>
<body>
    <a href="javascript:history.back();" class="back-btn">
        <i class="fas fa-arrow-left"></i> 返回
    </a>
    <header class="header"><!-- ... 导航栏 ... --></header>

    <main class="main">
        <section class="service-hero shopping">
            <div class="container">
                <h1>宠物用品代购</h1>
                <p>精选全球优质宠物用品，为您提供一站式代购服务，省时省心。</p>
            </div>
        </section>

        <div class="container service-layout">
            <div class="service-details">
                <h2><i class="fas fa-shopping-cart"></i> 热门商品</h2>
                <p>我们为您精心挑选了最受欢迎的宠物主粮、零食、玩具和日用品。</p>
                <div class="product-grid" id="product-grid">
                    <!-- 由JS动态渲染 -->
                </div>
            </div>

            <div class="booking-form-container">
                <div class="booking-form">
                    <h2><i class="fas fa-truck"></i> 配送信息</h2>
                    <form onsubmit="return false;">
                        <div class="form-group">
                            <h4>购物车</h4>
                            <p>您已选择 <span id="cartItemCount">0</span> 件商品</p>
                            <p>总计：<span id="cartTotalPrice" style="color: #d4a200; font-weight:bold;">¥0.00</span></p>
                        </div>
                        <div class="form-group"><label>选择配送地址</label><select required><option value="">请选择</option><option>家庭地址1</option></select></div>
                        <div class="form-group"><label>期望送达时间</label><select required><option value="">请选择</option><option>工作日</option><option>周末</option><option>均可</option></select></div>
                        <div class="form-group"><label>备注</label><textarea rows="2"></textarea></div>
                        <button type="submit" class="btn btn-primary btn-large" onclick="createOrder()">立即下单</button>
                    </form>
                </div>
            </div>
        </div>
    </main>

    <!-- 购物车图标 -->
    <div class="cart-icon" onclick="toggleCart()">
        <i class="fas fa-shopping-cart"></i>
        <div class="cart-badge" id="cart-badge">0</div>
    </div>

    <!-- 购物车弹窗 -->
    <div class="cart-modal" id="cart-modal">
        <div class="cart-content">
            <div class="cart-header">
                <h3><i class="fas fa-shopping-cart"></i> 购物车</h3>
                <button class="close-btn" onclick="toggleCart()">×</button>
            </div>
            <div class="cart-body" id="cart-body">
                <!-- 购物车商品列表 -->
            </div>
            <div class="cart-footer" id="cart-footer">
                <!-- 购物车底部操作 -->
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.0/dist/axios.min.js"></script>
    <script src="js/api.js"></script>
    <script>
        // 全局变量
        let products = [];
        let cartItems = [];

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', async () => {
            await loadProducts();
            await loadCart();
        });

        // 加载商品列表
        async function loadProducts() {
            const productGrid = document.getElementById('product-grid');
            productGrid.innerHTML = '<div class="loading">加载商品中...</div>';
            
            try {
                const response = await petHouseAPI.shop.products.getAll();  
                products = response.data || [];
                console.log("products=",products);
                
                renderProducts();
            } catch (error) {
                console.error('加载商品失败:', error);
                productGrid.innerHTML = '<div class="error">商品加载失败，请刷新重试</div>';
            }
        }

        // 渲染商品列表
        function renderProducts() {
            const productGrid = document.getElementById('product-grid');
            
            if (products.length === 0) {
                productGrid.innerHTML = '<div class="loading">暂无商品</div>';
                return;
            }

            const html = products.map(product => `
                <div class="product-card">
                    <img src="${product.imageUrl || 'images/product1.jpg'}" alt="${product.name}" class="product-image">
                    <div class="product-info">
                        <h4>${product.name}</h4>
                        <div class="product-price">¥${product.price?.toFixed(2) || '0.00'}</div>
                        <button class="btn btn-primary add-to-cart" onclick="addToCart(${product.id})">加入购物车</button>
                    </div>
                </div>
            `).join('');
            
            productGrid.innerHTML = html;
        }

        // 加载购物车
        async function loadCart() {
            try {
                const response = await petHouseAPI.shop.cart.getAll();
                cartItems = response.data || [];
                updateCartDisplay();
            } catch (error) {
                console.error('加载购物车失败:', error);
            }
        }

        // 更新购物车显示
        function updateCartDisplay() {
            const itemCount = cartItems.length;
            const totalPrice = cartItems.reduce((sum, item) => {
                const product = products.find(p => p.id === item.productId);
                return sum + (product?.price || 0) * item.quantity;
            }, 0);

            document.getElementById('cartItemCount').textContent = itemCount;
            document.getElementById('cartTotalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
            
            // 更新购物车图标徽章
            document.getElementById('cart-badge').textContent = itemCount;
            
            // 更新购物车弹窗内容
            renderCartModal();
        }

        // 渲染购物车弹窗
        function renderCartModal() {
            const cartBody = document.getElementById('cart-body');
            const cartFooter = document.getElementById('cart-footer');
            
            if (cartItems.length === 0) {
                cartBody.innerHTML = '<div class="empty-cart">购物车为空</div>';
                cartFooter.innerHTML = '';
                return;
            }
            console.log("cartItems=",cartItems);
            console.log("products=",products);
        
            // 渲染购物车商品列表
            const cartItemsHtml = cartItems.map(item => {
                console.log("item=",item);
                
                console.log("item.productName=",item.productName);
                
                const product = products.find(p => p.name === item.productName);
                
                
                if (!product) return '';
                
                return `
                    <div class="cart-item">
                        <img src="${product.imageUrl || 'images/product1.jpg'}" alt="${product.name}" class="cart-item-image">
                        <div class="cart-item-info">
                            <div class="cart-item-name">${product.name}</div>
                            <div class="cart-item-price">¥${product.price?.toFixed(2) || '0.00'}</div>
                            <div class="cart-item-quantity">
                                <button class="quantity-btn" onclick="updateCartQuantity(${item.cartId}, ${item.quantity - 1})">-</button>
                                <span>${item.quantity}</span>
                                <button class="quantity-btn" onclick="updateCartQuantity(${item.cartId}, ${item.quantity + 1})">+</button>
                                <button class="delete-btn" onclick="removeFromCart(${item.cartId})">删除</button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
            cartBody.innerHTML = cartItemsHtml;

            // 计算总价
            const totalPrice = cartItems.reduce((sum, item) => {
                const product = products.find(p => p.name === item.productName);
                return sum + (product?.price || 0) * item.quantity;
            }, 0);

            // 渲染购物车底部
            cartFooter.innerHTML = `
                <div class="cart-total">
                    <span>总计：</span>
                    <span>¥${totalPrice.toFixed(2)}</span>
                </div>
                <div class="cart-actions">
                    <button class="btn btn-outline" onclick="clearCart()">清空购物车</button>
                    <button class="btn btn-primary" onclick="checkout()">去结算</button>
                </div>
            `;
        }

        // 切换购物车弹窗显示/隐藏，并每次打开时刷新数据
        async function toggleCart() {
            const modal = document.getElementById('cart-modal');
            if (!modal.classList.contains('show')) {
                // 每次打开弹窗都重新加载购物车和商品数据
                await loadProducts();
                await loadCart();
            }
            modal.classList.toggle('show');
        }

        // 更新购物车商品数量
        async function updateCartQuantity(cartId, newQuantity) {
            if (newQuantity <= 0) {
                await removeFromCart(cartId);
                return;
            }
            
            try {
                await petHouseAPI.shop.cart.update(cartId, newQuantity);
                await loadCart();
            } catch (error) {
                console.error('更新购物车失败:', error);
                alert('更新失败，请重试');
            }
        }

        // 从购物车移除商品
        async function removeFromCart(cartId) {
            try {
                await petHouseAPI.shop.cart.delete(cartId);
                await loadCart();
            } catch (error) {
                console.error('移除商品失败:', error);
                alert('移除失败，请重试');
            }
        }

        // 清空购物车
        async function clearCart() {
            if (!confirm('确定要清空购物车吗？')) return;
            
            try {
                await petHouseAPI.shop.cart.clear();
                await loadCart();
            } catch (error) {
                console.error('清空购物车失败:', error);
                alert('清空失败，请重试');
            }
        }

        // 去结算
        function checkout() {
            toggleCart(); // 关闭购物车弹窗
            // 滚动到下单区域
            document.querySelector('.booking-form-container').scrollIntoView({ behavior: 'smooth' });
        }

        // 添加到购物车
        async function addToCart(productId) {
            try {
                await petHouseAPI.shop.cart.add(productId, 1);
                await loadCart(); // 重新加载购物车
                alert('已添加到购物车！');
            } catch (error) {
                console.error('添加到购物车失败:', error);
                alert('添加失败，请重试');
            }
        }

        // 创建订单
        async function createOrder() {
            if (cartItems.length === 0) {
                alert('购物车为空，请先添加商品');
                return;
            }

            const addressSelect = document.querySelector('select');
            const remarkTextarea = document.querySelector('textarea');
            
            if (!addressSelect.value) {
                alert('请选择配送地址');
                return;
            }

            try {
                await petHouseAPI.shop.orders.create(addressSelect.value, remarkTextarea.value);
                alert('订单创建成功！');
                // 清空购物车显示
                cartItems = [];
                updateCartDisplay();
            } catch (error) {
                console.error('创建订单失败:', error);
                alert('订单创建失败，请重试');
            }
        }
    </script>
</body>
</html> 